package com.free.bsf.eureka.client.filter;

import com.free.bsf.core.util.ContextUtils;
import com.netflix.appinfo.InstanceInfo;
import lombok.val;
import org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class EurekaStatusFilter implements Filter {
    /**
     * 1、调用/service-registry端点将状态置为 OUT_OF_SERVICE
     * 2、sleep 缓存刷新时间 + 单个请求处理时间
     * 3、调用 /service-registry端点将状态置为 CANCEL_OVERRIDE，其实就是向Server端发送DELETE overriddenstatus的请求，这会让Server端 status=UNKNOWN 且 overriddenstatus=UNKNOWN
     * 4、使用 /shutdown端点 或 暴利kill -9终止服务
     * 5、发版部署后，启动服务注册到Eureka Server，服务状态变为UP
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        val request = (HttpServletRequest) servletRequest;
        val response = (HttpServletResponse) servletResponse;
        val conetextPath = org.springframework.util.StringUtils.trimTrailingCharacter(request.getContextPath(), '/');
        val uri = request.getRequestURI();
        if (uri.startsWith(conetextPath + "/bsf/eureka/changeClientStatus/")) {
            EurekaRegistration registration = ContextUtils.getBean(EurekaRegistration.class,false);
            if(registration!=null) {
//                val status = request.getParameter("status");
                String status = null;
                //匹配请求修改的状态
                if (uri.toLowerCase().contains("up")){
                    status = "UP";
                }if (uri.toLowerCase().contains("down")){
                    status = "DOWN";
                }if (uri.toLowerCase().contains("starting")){
                    status = "STARTING";
                }if (uri.toLowerCase().contains("out_of_service")){
                    status = "OUT_OF_SERVICE";
                }if (uri.toLowerCase().contains("unknown")){
                    status = "UNKNOWN";
                }
                InstanceInfo.InstanceStatus newStatus = InstanceInfo.InstanceStatus.toEnum(status);
                registration.getEurekaClient().setStatus(newStatus, registration.getApplicationInfoManager().getInfo());
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().append(registration.getEurekaClient().getInstanceRemoteStatus().name());
                response.getWriter().flush();
                response.getWriter().close();
            }
        } else {
            chain.doFilter(servletRequest, servletResponse);
        }

    }
    @Override
    public void destroy() {

    }
}
